/*
 * Sets up the model with client-side metadata 
 * and any other model extensions we need (none so far)
 */
(function (){
    'use strict';
    angular.module('app').factory('model', ['$log','$q','breeze','config', service]);

    function service($log, $q, breeze, config){
        var model =  {
            setModel: setModel
        };
        return model;
        //////////////////////

        function setModel(manager) {
            // could do more to the model but we don't in this example
            return getMetadata(manager); 
        }

        function getMetadata(manager) {
            if(config.hasServerMetadata){
                // Get metadata from the server
                return manager.metadataStore
                    .fetchMetadata(manager.dataService)
                    .then(function(){return manager;})
                    .catch(metadataFetchFailed);
       
            } else {
                // Get metadata from the client
                addClientMetadata(manager); 
                return $q.when(manager) ;                      
            }

            function metadataFetchFailed(error){
                var err = 'Metadata fetch failed.\nIs the server running?';
                $log.error(err+'\n'+ error);
                return $q.reject(err);
            }
        }

        function addClientMetadata(manager) {
            var DT = breeze.DataType;
            var store = manager.metadataStore;
            var helper = new breeze.config.MetadataHelper(
                'Model', 
                breeze.AutoGeneratedKeyType.Identity);

            // Associate the metadata with the manager's data service
            store.addDataService(manager.dataService);

            addTodoItemType();

            function addTodoItemType() {
                var entityType = {
                    name: "TodoItem",
                    defaultResourceName: "TodoItem",
                    dataProperties: {
                        id:       { type: DT.Guid },
                        text:     { max: 50, required: true  },
                        complete: { type: DT.Boolean, required: true }
                    }
                };

                helper.addTypeToStore(store, entityType);

                return entityType;
            }
        }
    }
})();
